package cn.icanci.ladybird.controller;

import cn.icanci.ladybird.common.result.JsonData;
import cn.icanci.ladybird.pojo.dto.UserOrderDTO;
import cn.icanci.ladybird.service.user.UserOrderService;
import cn.icanci.ladybird.service.util.AlipayService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: icanci
 * @date: Created in 2020/10/13 10:22
 * @classAction: 支付宝支付接口
 */
@SuppressWarnings("all")
@Controller
@Slf4j
@RequestMapping("/api/v1/pri/common")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private UserOrderController userOrderController;
    @Autowired
    private UserOrderService userOrderService;

    /**
     * 付款界面
     *
     * @param httpResponse 响应
     * @param request      请求
     * @param orderInfoId  订单id
     * @throws IOException 异常
     */
    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse, HttpServletRequest request, Long orderInfoId) throws IOException {
        alipayService.alipay(httpResponse, request, orderInfoId);
    }

    @RequestMapping("/to-alipay")
    public void toAlipay(HttpServletResponse httpResponse, HttpServletRequest request, Long orderInfoId) throws Exception {
        alipayService.toAlipay(httpResponse, request, orderInfoId);
    }

    @RequestMapping("/return_url")
    public void returnUrl(Model model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        log.info("AlipayController.returnUrl - 1");
        JsonData jsonData = alipayService.returnUrl(request, response);
        if (jsonData != null && jsonData.getCode().equals(0)) {
            // 支付成功 跳转到个人订单页面
            // return userOrderController.adminTicketList(model, null, null);
            // 页面参数，然后在Service进行分页
            PageInfo<UserOrderDTO> ticketDetailsPageInfo = userOrderService.queryAllByNotObject(1L, null, null);
            JsonData jsonData2 = JsonData.builderSuccess(ticketDetailsPageInfo);
            model.addAttribute("jsonData", jsonData2);
            log.info("AlipayController.returnUrl - 2");
            response.sendRedirect("/api/v1/pri/user/order");
            // return "user/my-order";
        } else {
            // 支付失败 跳转到订单页面
            response.sendRedirect("/api/v1/pub/user/500");
            // return "user/500";
        }
    }
}
